<?php
namespace App\Models;

use App\Models\System\Term;
use App\Models\System\User;
use App\Models\Teaching\HomeworkInfo;
use App\Models\Teaching\TeachingActivity;
use App\Models\Teaching\TeachingComment;
use App\Models\Teaching\TeachingHomework;
use App\Models\Traits\HasManagable;
use App\Models\Traits\HasManyFiles;

class ActivityInfo extends Model
{
    use HasManyFiles, HasManagable;
    protected $table = 'activity_info';
    protected $guarded = [];
    protected $appends = [
        'publish_type_set', //pubications_publish_type
        'level_array',
        'course_set',
        'grade_array',
        'witness_set',
        'awarding_unit_set',
        'guided_teacher_set',
        'guided_teacher_school_set',
        'proof_material_array',
        'category_array',
        'reception_class_set',
        'class_item_set',
        'participants_users',
        'activity_date_status',
        'headdepart_set'
    ];

    protected $casts = [
//        'proof_material' => 'array'
    ];
    public function term()
    {
        return $this->hasOne(Term::class, 'id', 'data_version_id');
    }

    public function instance()
    {
        return $this->hasOne(FormInstance::class, 'id', 'form_instance_id');
    }

    public function forminstance()
    {
        return $this->belongsTo(FormInstance::class, 'form_instance_id', 'id');
    }

    public function participants()
    {
        return $this->hasMany(Participant::class, 'activity_info_id');
    }

    public function stages()
    {
        return $this->hasMany(StudyStage::class, 'activity_id');
    }

    public function teachingActivity()
    {
        return $this->hasOne(TeachingActivity::class, 'activity_id');
    }

    public function homework()
    {
        return $this->hasMany(TeachingHomework::class, 'activity_id');
    }

    public function homeworkInfo()
    {
        return $this->hasMany(HomeworkInfo::class, 'activity_id');
    }

    //主持人
    public function compere()
    {
        return $this->hasMany(Participant::class, 'activity_info_id')->where('participant_type', 'COMPERE')->with('user:id,user_id,group_id,nickname');
    }
    //远程关联用户表
    public function compereUser()
    {
        return $this->hasManyThrough(User::class,  Participant::class, 'activity_info_id', 'id', 'id', 'user_id')->where('participant_type', 'COMPERE');
    }
    //参与人
    public function participant()
    {
        return $this->hasMany(Participant::class, 'activity_info_id')->where('participant_type', 'PARTICIPANT')->with('user:id,user_id,group_id,nickname');
    }
    //远程关联用户表
    public function participantUser()
    {
        return $this->hasManyThrough(User::class,  Participant::class, 'activity_info_id', 'id', 'id', 'user_id')->where('participant_type', 'PARTICIPANT');
    }
    //远程关联用户表
    public function joinUser()
    {
        return $this->hasManyThrough(User::class,  Participant::class, 'activity_info_id', 'id', 'id', 'user_id');
    }

    // 教研活动评论
    public function comments()
    {
        return $this->hasMany(TeachingComment::class, 'activity_id')->orderBy('id', 'desc');
    }

    //创建人
    public function creator()
    {
        return $this->hasOne(User::class, 'id', 'creator_id');
    }

    //创建人
    public function partNames()
    {
        return $this->hasOne(ActivityInfoPartNames::class, 'activity_info_id', 'id');
    }

    public function scopeManageable($query)
    {
        return $this->addManagableFilter($query, 'check_state', ['create_by', 'major_tid', 'apart_tid']);
    }


    //活动时间状态------针对教研活动
    public function getActivityDateStatusAttribute()
    {
        $now = now();
        $result = "-";
        $beginDate = !empty($this->attributes['begin_date']) ? $this->attributes['begin_date'] : '';
        $endDate = !empty($this->attributes['end_date']) ? $this->attributes['end_date'] : '';
        if(!$beginDate || !$endDate){
            return $result;
        }

        if($now->lt($beginDate)) {
            $result = "未开始";
        }

        if($now->gte($beginDate) && $now->lte($endDate)) {
            $result = "进行中";
        }

        if($now->gt($endDate)) {
            $result = "已结束";
        }

        return $result;
    }

    public function getParticipantsUsersAttribute(){
        $users = !empty($this->relations['participants']) ? $this->relations['participants'] : '';
        if(!$users){
            return [];
        }

        $result = [];
        $result['pere'] = $users->where('participant_type', 'COMPERE')->pluck('user_id')->toArray();
        $result['pant'] = $users->where('participant_type', 'PARTICIPANT')->pluck('user_id')->toArray();
        if($result['pant']){
            $result['user_str'] =  implode(',',User::whereIn('id',$result['pant'])->pluck('nickname')->toArray());
        }else{
            $result['user_str'] =  '';
        }
        return $result;
    }


    public function getProofMaterialArrayAttribute(){
        $proofMaterial = !empty($this->attributes['proof_material'])?$this->attributes['proof_material']:'';
        if(!$proofMaterial){
            return [];
        }

        $files = json_decode($proofMaterial, true);
        $files_id = array_column($files,'id');
        $file = File::whereIn('id',$files_id)->get()->toArray();
        $file = array_column($file,null,'id');

       // dd($files,$file);
        foreach($files as $k => $f) {
            //$file = File::whereId($f['id'])->first();

            $files[$k]['file_info'] = $file[$f['id']];
            $files[$k]['file_origin'] = [
                'files_id' => $f['files_id'],
                'file_name' => $f['fileName'],
                'size' => $file[$f['id']]['file_size'],
                'url' => $file[$f['id']]['file_dir'] . $file[$f['id']]['file_path'],
                'id' => $f['id']
            ];
        }

        return $files;
    }

    public function getPublishTypeSetAttribute(){
        return $this->getFieldValue('pubications_publish_type');
    }

    public function getLevelArrayAttribute(){
        return $this->getFieldValue('level');
    }

    public function getCourseSetAttribute(){
        return $this->getFieldValue('course');
    }

    public function getGradeArrayAttribute(){
        return $this->getFieldValue('grade');
    }

    public function getWitnessSetAttribute(){
        $witness = !empty($this->attributes['witness']) ? $this->attributes['witness'] : '';

        if(!$witness) {
            return [];
        }

        $set = json_decode($witness, true);

        if(isset($set['zmr'])) {
            $set['zmrs'] = explode(',', $set['zmr']);
        }

        return $set;
    }

    public function getHeaddepartSetAttribute(){
        $hd = !empty($this->attributes['head_of_departs']) ? $this->attributes['head_of_departs'] : '';

        if(!$hd) {
            return '';
        }

        $result['origin'] = $hd;
        $result['fzrs'] = explode(',', $hd);

        return $result;
    }

    public function getAwardingUnitSetAttribute(){
        return $this->getFieldValue('awarding_unit');
    }

    public function getGuidedTeacherSetAttribute(){
        return $this->getFieldValue('guided_teacher');
    }

    public function getGuidedTeacherSchoolSetAttribute(){
        return $this->getFieldValue('guided_teacher_school');
    }

    public function getCategoryArrayAttribute(){
        return $this->getFieldValue('category');
    }

    public function getReceptionclassSetAttribute(){
        return $this->getFieldValue('reception_class');
    }

    public function getClassItemSetAttribute(){
        return $this->getFieldValue('class_item');
    }

    public function getFieldValue($field)
    {
        $f = !empty($this->attributes[$field]) ? $this->attributes[$field] : '';

        if(!$f){
            return [];
        }

        return json_decode($f, true);
    }

    public function setFilesIdAttribute($filesIdArr)
    {
        $this->files()->whereNotIn('id', $filesIdArr)->update(['ilk_type' => null, 'ilk_id' => null]);
        $this->files()->saveMany(Files::query()->whereIn('id', $filesIdArr)->get());
    }
}

?>
